<template>
    <el-card shadow="never">
        <div class="edu-page-title">申请明细</div>
        <el-form
            ref="applyForm"
            :model="applyForm"
            label-width="150px"
            label-suffix="："
            :rules="rules"
        >
            <el-row :gutter="20" >
                <el-col :span="8" v-if="showPleaseNum">
                    <el-form-item label="请示文号" prop="pleaseNum">
                        <el-input v-model="applyForm.pleaseNum" style="width:100%" maxlength="30" />
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="type == 1">
                    <el-form-item label="发文编号" prop="issueNum">
                        <el-input v-model="applyForm.issueNum" style="width:100%" maxlength="30" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="申请原因" prop="applyReason">
                        <el-select v-model="applyForm.applyReason" clearable style="width:100%">
                            <el-option
                                v-for="item in options.applyReason"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 培养层次 -->
                    <el-form-item label="硕士培养层次" prop="masTrainingLevel">
                        <el-select
                            v-model="applyForm.masTrainingLevel"
                            style="width:100%"
                            clearable
                            @change="getGraduateDegree()"
                            collapse-tags
                        >
                            <el-option
                                v-for="item in options.trainingLevel"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!-- 培养类别 -->
                    <el-form-item label="硕士培养类别" prop="masTrainingCategory">
                        <el-select
                            v-model="applyForm.masTrainingCategory"
                            style="width:100%"
                            clearable
                        >
                            <el-option
                                v-for="item in options.trainingCategory"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <!-- 学位类型 -->
                    <el-form-item label="硕士学位类型" prop="masDegreeType">
                        <el-select
                            v-model="applyForm.masDegreeType"
                            style="width:100%"
                            @change="getGraduateDegree()"
                            clearable
                        >
                            <el-option
                                v-for="item in options.degreeType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="硕士专业" prop="masProfession">
                        <el-select
                            v-model="applyForm.masProfession"
                            clearable
                            filterable
                            style="width:100%"
                        >
                            <el-option
                                v-for="item in options.masProfessions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="硕士年级" prop="masGrade">
                        <el-date-picker
                            clearable
                            v-model="applyForm.masGrade"
                            value-format="yyyy"
                            type="year"
                            :placeholder="$t('message.plzSelect')"
                            style="width: 100%"
                            @change="handleTime"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="硕士导师" prop="masTeacherId">
                        <select-For-Page
                            URL="/api/studentservice/userInfo/studentOrTeacherPageList"
                            v-model="applyForm.masTeacherId"
                            :queryType="1"
                            :val="applyForm.masTeacherId"
                            @returnVal="getTeacherCode"
                            :ifDisabled="teacherId?true:false">
                        </select-For-Page>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="24">
                <!-- <el-col :span="8">
                    <el-form-item label="硕士年级" prop="masGrade">
                        <el-date-picker
                            clearable
                            v-model="applyForm.masGrade"
                            value-format="yyyy"
                            type="year"
                            :placeholder="$t('message.plzSelect')"
                            style="width: 100%"
                            @change="handleTime"
                        />
                    </el-form-item>
                </el-col> -->
                <el-col :span="8">
                    <el-form-item label="硕士入学季节" prop="masEnrolSeason">
                        <el-select
                            v-model="applyForm.masEnrolSeason"
                            clearable
                            style="width:100%"
                            @change="handleTime"
                        >
                            <el-option
                                v-for="item in options.enrolSeason"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="博转硕开始时间" prop="masStartTime">
                        <el-input v-model="applyForm.masStartTime" style="width: 100%" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="硕士阶段最晚结束时间" prop="masEndTime" label-width="170px">
                        <el-input v-model="applyForm.masEndTime" style="width: 100%" disabled></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="16">
                    <el-form-item label="原因说明" prop="reasonDescri">
                        <el-input
                            type="textarea"
                            rows="3"
                            v-model="applyForm.reasonDescri"
                            maxlength="200"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="申请材料" prop="evidences">
                        <el-upload
                            ref="uploadBtn"
                            id="upload-btn"
                            :data="{bucketname: 'face', folderpath: 'file'}"
                            action="/api/commonservice/obsfile/uploadfile"
                            :auto-upload="false"
                            :on-success="handleUploadSuccess"
                            :on-remove="handleUploadRemove"
                            :on-error="handleUploadError"
                            :on-exceed="handleUploadExceed"
                            :on-change="handleUploadChange"
                            multiple
                            :limit="5"
                            :file-list="fileList"
                        >
                            <div>
                                <el-button size="small" type="primary">上传附件</el-button>
                                <div
                                    slot="tip"
                                    class="el-upload__tip"
                                >上传要求：请上传jpg/png/word/pdf/xls等文件，且不超过5M</div>
                            </div>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div align="right">
            <el-button @click="handleReturn">{{$t('message.return')}}</el-button>
            <el-button v-if="showSaveBtn" type="primary" @click="handleSave">{{$t('message.save')}}</el-button>
            <el-button type="primary" @click="handleSubmit">{{$t('message.submit')}}</el-button>
        </div>
        <edu-dialog
            :title="$t('message.prompt')"
            width="450px"
            :visible.sync="showDialog"
            :showFooter="false"
        >
            <div>返回将不会保存当前填写数据，是否确定？</div>
            <div class="float-right" style="margin:25px 0 0 0">
                <el-button @click="showDialog=false">{{$t("message.cancel")}}</el-button>
                <el-button @click="confirmReturn" type="primary">{{$t("message.confirm")}}</el-button>
                <el-button v-if="showSaveBtn" @click="saveAndClose" type="primary">保存并关闭</el-button>
            </div>
            <div style="clear:both"></div>
        </edu-dialog>
    </el-card>
</template>
<script>
import {
    getMasTime,
    submitManage,
    batchSubmitManage,
    addmanage,
    getStudentInfo,
    getGraduateDegreeByColleges
} from "common/src/api/culture/change";
import selectForPage from 'common/src/components/common/selectForPage'
export default {
    components: {
        'select-For-Page': selectForPage,
    },
    name: "ApplyForm",
    props: {
        options: {},
        showPleaseNum: {
            default: false,
            type: Boolean
        },
        type: {
            default: null,
            required: true
        },
        submissionType: {
            default: null,
            required: true
        },
        showSaveBtn: {
            default: false,
            type: Boolean
        },
        students: {
            default: null
        },
        pageFrom: {
            default: null
        },
        editForm: {
            default: null
        },
        masProfession: {
            default: null
        },
        teacherId: {
            default: null
        }
    },
    data: function() {
        return {
            fileList: [],
            fileSuccesList: [],
            applyForm: {
                applyReason: null,
                masProfession: null,
                masTeacherId: null,
                masGrade: null,
                masEnrolSeason: null,
                masStartTime: null,
                masEndTime: null,
                reasonDescri: null,
                evidences: null,
                evidence: null,
                issueNum: null, // 发文编号
                pleaseNum: null,
                masTrainingLevel: "4", //培养层次
                masTrainingCategory: '3', //培养类别
                masDegreeType: '', //学位类型
            },
            options: {
                trainingLevel: [],
                trainingCategory: [],
                degreeType: [],
                masProfessions: []
            },
            isDraft: false, //是否草稿
            fileSuccessStatus: "success",
            rules: {
                applyReason: {
                    required: true,
                    message: "必须选择申请原因",
                    trigger: "change"
                },
                masProfession: {
                    required: true,
                    message: "必须选择硕士专业",
                    trigger: "change"
                },
                masTeacherId: {
                    required: true,
                    message: "必须选择硕士导师",
                    trigger: "change"
                },
                masGrade: {
                    required: true,
                    message: "必须选择硕士年级",
                    trigger: "change"
                },
                masTrainingLevel: {
                    required: true,
                    message: "必须选择培养层次",
                    trigger: "change"
                },
                masTrainingCategory: {
                    required: true,
                    message: "必须选择培养类别",
                    trigger: "change"
                },
                masDegreeType: {
                    required: true,
                    message: "必须选择学位类型",
                    trigger: "change"
                },
                issueNum: {
                    required: true,
                    message: "必须输入发文编号",
                    trigger: "change"
                },
                masEnrolSeason: {
                    required: true,
                    message: "必须选择入学季节",
                    trigger: "change"
                },
                // masStartTime: {
                //     required: true,
                //     message: "必须选择硕士阶段开始时间",
                //     trigger: "change"
                // },
                // masEndTime: {
                //     required: true,
                //     message: "必须选择硕士阶段结束时间",
                //     trigger: "change"
                // },
                reasonDescri: {
                    required: true,
                    message: "必须填写原因说明",
                    trigger: "change"
                },
                pleaseNum: {
                    required: this.type == '1'?false:true,
                    message: "必须填写请示文号",
                    trigger: "change"
                },
                evidences: [
                    {
                        required: true,
                        message: "必须上传申请材料",
                        trigger: "change"
                    },
                    { validator: this.handleFileCheck, trigger: "change" }
                ]
            },
            showDialog: false
        };
    },
    mounted() {
            this.applyForm.masProfession = this.masProfession;
            this.applyForm.masTrainingLevel = "4";
            this.applyForm.masTrainingCategory = "3";
            this.applyForm.masDegreeType = this.students[0].degreeType;
        if (this.teacherId) {
            this.applyForm.masTeacherId = this.teacherId;
        }
         
        if (this.editForm) {
            Object.keys(this.applyForm).forEach(key => {
                if (this.editForm.hasOwnProperty(key)) {
                    this.applyForm[key] =
                        typeof this.editForm[key] === "number"
                            ? this.editForm[key].toString()
                            : this.editForm[key];
                }
            });
            if(this.applyForm.evidence) {
                this.fileList = JSON.parse(this.applyForm.evidence).map(file => {
                    return { name: file.name };
                });
               this.applyForm.evidences = JSON.parse(this.applyForm.evidence).map(file => {
                    return { url: file.url };
                }); 
            }
        }
    },
    methods: {
        // 获取所属学院、姓名
        getTeacherCode(val) {
            if (val) {
                this.applyForm.masTeacherId = val
                 
            } else {
                this.applyForm.masTeacherId = ''
            }
        },
        getGraduateDegree() {
            if(this.students && this.students[0].faculty) {
                this.applyForm.masProfession = ""
                let parm = {
                        trainingLevel: this.applyForm.masTrainingLevel,
                        facultys: [this.students[0].faculty],
                        types: [this.applyForm.masDegreeType]
                    }
                    getGraduateDegreeByColleges(parm).then(resT => {
                    if (resT.code == 200) {
                        let language = this.$store.getters.language || "cn";
                        this.options.masProfessions = resT.data.map(row => {
                            return {
                                label:
                                    (language == "cn" ? row.nameCN : row.nameEn) +
                                    " (" +
                                    row.code +
                                    ")",
                                value: row.code
                            };
                        });
                    }
                });
            } else {
                return false
            }
        },

        init() {
            //初始化申请明细
            this.applyForm.pleaseNum = null;
            this.applyForm.applyReason = null;
            this.applyForm.masProfession = this.masProfession;
            this.applyForm.masTeacherId = this.masTeacherId;
            this.applyForm.issueNum = null;
            this.applyForm.masDegreeType = null;
            this.applyForm.masTrainingLevel = "4";
            this.applyForm.masTrainingCategory = "3";
            this.applyForm.masGrade = null;
            this.applyForm.reasonDescri = null;
            this.applyForm.masEnrolSeason = null;
            this.applyForm.masStartTime = null;
            this.applyForm.masEndTime = null;
            this.applyForm.evidences = null;
            this.$nextTick(() => {
                this.$refs.applyForm.clearValidate();
            });
            if (this.$refs.uploadBtn) {
                this.$refs.uploadBtn.clearFiles();
                this.fileList = [];
                this.fileSuccesList.length = 0;
            }
        },
        handleReturn() {
            let changed = false;
            //新增
            if (this.editForm == null) {
                if (
                    Object.keys(this.applyForm).some(
                        key =>
                            this.applyForm[key] != null &&
                            _.trim(this.applyForm[key]) != ""
                    )
                ) {
                    changed = true;
                }
            } else {
                Object.keys(this.applyForm).forEach(key => {
                    if (
                        this.editForm.hasOwnProperty(key) &&
                        this.applyForm[key] != this.editForm[key]
                    ) {
                        changed = true;
                    }
                });
            }
            if (changed) {
                this.showDialog = true;
            } else {
                this.$emit("close");
            }
        },
        confirmReturn() {
            this.showDialog = false;
            this.$emit("close");
        },
        saveAndClose() {
            this.showDialog = false;
            if (this.showSaveBtn) {
                this.handleSave();
            } else {
                this.handleSubmit();
            }
        },
        handleSave() {
            this.$refs.applyForm.validate(async valid => {
                if (!valid) {
                    return;
                }
                let flag = true
                if(this.pageFrom === 'apply') {
                    await getStudentInfo(
                        this.students[0].studentId ? this.students[0].studentId : ''
                    ).catch(err=> {
                        flag = false
                    });
                }
                if(flag) {
                    this.isDraft = true;
                    //判断是否存在未上传文件
                    if (!this.fileList.some(f => f.percentage != null)) {
                        let files = this.fileList.map(f => {
                            return f.name;
                        });
                        this.saveOrSubmit(files);
                    } else {
                        this.fileSuccesList.length = 0;
                        this.$refs.uploadBtn.submit();
                    }
                }
            });
        },
        handleSubmit() {
            this.$refs.applyForm.validate(async valid => {
                if (!valid) {
                    return;
                }
                let flag = true
                if(this.pageFrom === 'apply') {
                    await getStudentInfo(
                        this.students[0].studentId ? this.students[0].studentId : ''
                    ).catch(e => {
                        flag = false
                    })
                }
                if(flag) {
                this.isDraft = false;
                //判断是否存在未上传文件
                if (!this.fileList.some(f => f.percentage != null)) {
                    let files = this.fileList.map(f => {
                        return f.name;
                    });
                    this.saveOrSubmit(files);
                } else {
                    this.fileSuccesList.length = 0;
                    this.$refs.uploadBtn.submit();
                }
            }
            });
        },
        handleTime() {
            if (
                this.applyForm.masGrade != null &&
                this.applyForm.masGrade != "" &&
                this.applyForm.masEnrolSeason != null &&
                this.applyForm.masEnrolSeason != ""
            ) {
                getMasTime({
                    masGrade: this.applyForm.masGrade,
                    masEnrolSeason: this.applyForm.masEnrolSeason
                }).then(res => {
                    if (res.code == 200) {
                        this.applyForm.masStartTime = res.data.masStartTime;
                        this.applyForm.masEndTime = res.data.masEndTime;
                    }
                });
            } else {
                this.applyForm.masStartTime = null;
                this.applyForm.masEndTime = null;
            }
        },
        handleUploadExceed() {
            this.$message({
                type: "warning",
                message: "超出文件上传个数"
            });
        },
        handleUploadError(err) {
            this.$message({
                type: "error",
                message: err
            });
        },
        handleUploadSuccess(response, file, fileList) {
            this.fileSuccesList.push(file);
            if (
                this.fileSuccesList.length ===
                this.fileList.filter(f => f.percentage != null).length
            ) {
                let files = this.fileSuccesList.map(f => {
                    return f.response.data[f.name].objectkey;
                });
                let applyFiles = this.fileSuccesList.map(f => {
                    return {
                        url: f.response.data[f.name].objectkey,
                        name: f.name
                        }
                });
                this.fileList.forEach(file => {
                    if (
                        file.percentage == null &&
                        file.status === this.fileSuccessStatus
                    ) {
                        files.push(file.name);
                    }
                });
                this.saveOrSubmit(files,applyFiles);
            }
        },
        saveOrSubmit(files,applyFiles) {
            let fn = res => {
                if (res.code == 200) {
                    this.$message({
                        type: this.fileSuccessStatus,
                        message: this.isDraft
                            ? this.$t("message.saveSuccess")
                            : this.$t("message.submitSuccess")
                    });
                    this.$emit("success");
                }
            };
            let params = _.cloneDeep(this.applyForm);
            params.evidence = JSON.stringify(applyFiles)
            params.submissionType = this.submissionType
            if (this.students.length == 1) {
                params.evidences = files;
                params.studentId = this.students[0].studentId;
                params.permitType = this.students[0].permitType;
                if (this.isDraft) {
                    params.id = this.editForm ? this.editForm.id : null;
                    addmanage(params).then(fn);
                } else {
                    params.id = this.editForm ? this.editForm.id : null;
                    submitManage(params).then(fn);
                }
            } else {
                params.evidences = files;
                params.studentInfoList = this.students.map(s => {
                    return {
                        studentId: s.studentId,
                        permitType: s.permitType
                    };
                });
                batchSubmitManage(params).then(fn);
            }
        },
        handleUploadRemove(file, fileList) {
            this.fileList = fileList;
            this.applyForm.evidences = fileList.length == 0 ? null : true;
            this.$refs.applyForm.validate();
        },
        handleUploadChange(file, fileList) {
            this.fileList = fileList;
            this.applyForm.evidences = true;
            this.$refs.applyForm.validate();
        },
        handleFileCheck(rule, value, callback) {
            let hasErr = false;
            //判断文件格式
            let exts = [
                ".doc",
                ".docx",
                ".jpg",
                ".png",
                ".xls",
                ".xlsx",
                ".pdf"
            ];
            for (const file of this.fileList) {
                if (file.status === this.fileSuccessStatus) {
                    continue;
                }
                let fileExtName = file.name
                    .substring(file.name.lastIndexOf("."))
                    .toLocaleLowerCase();
                if (!exts.includes(fileExtName)) {
                    hasErr = true;
                    break;
                }
            }
            if (hasErr) {
                callback(new Error("上传文件格式有错误"));
                return;
            }
            //判断文件大小
            for (const file of this.fileList) {
                if (file.status === this.fileSuccessStatus) {
                    continue;
                }
                if (!(file.size / 1024 / 1024 < 5)) {
                    hasErr = true;
                    break;
                }
            }
            if (hasErr) {
                callback(new Error("上传文件大小不能超过5M"));
                return;
            }
            callback();
        }
    }
};
</script>
<style lang="scss" scoped>
#upload-btn {
    button {
        float: left;
    }
    ::v-deep .el-upload {
        display: block;
    }
    ::v-deep .el-upload__tip {
        float: left;
        line-height: 30px;
        margin: 0 0 0 10px;
    }
    ::v-deep .el-upload-list {
        clear: both;
        width: 50%;
    }
}
</style>
